package com.tianzeculture.stagebao.activity.video;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.activity.artist.HotTagActivity;
import com.tianzeculture.stagebao.activity.artist.adapter.MyPushWorksAdapter;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.ArtistsDetailedBean;
import com.tianzeculture.stagebao.bean.ListpBean;
import com.tianzeculture.stagebao.bean.PhotoListEvent;
import com.tianzeculture.stagebao.bean.WorkTag;
import com.tianzeculture.stagebao.net.ArtistRestUsage;
import com.tianzeculture.stagebao.net.UserRestUsage;
import com.tianzeculture.stagebao.network.Request;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.ToastUtil;
import com.tianzeculture.stagebao.util.ImageUtils;
import com.tianzeculture.stagebao.util.Util;
import com.tianzeculture.stagebao.view.MyRecyclerview;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;


public class ModifyVideoActivity extends BaseActivity implements MyPushWorksAdapter.WorksListener {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_describe)
    EditText etDescribe;
    @BindView(R.id.tvCharmTag)
    TextView tvCharmTag;
    @BindView(R.id.tv_push)
    TextView tvPush;
    @BindView(R.id.layoutCharmTag)
    LinearLayout layoutCharmTag;
    @BindView(R.id.btnSave)
    Button btnSave;
    @BindView(R.id.ibtnDelete)
    ImageButton ibtnDelete;
    @BindView(R.id.my_recyclerview)
    MyRecyclerview mRecyclerview;

    boolean isVedio = true;
    List<WorkTag> charmPosition = new ArrayList<>();
    List<WorkTag> checkCharmPosition = null;
    String charm;
    private int pushPhotoId = 100;
    private int pushVedioId = 210;
    private int deletePicId = 310;
    private int myInfoId = 510;
    private int addPicId = 410;
    private int deleteAllId = 610;
    Map<String, String> params = new HashMap<>();
    ListpBean bean;
    @Request
    ArtistRestUsage artistRestUsage = null;
    @Request
    UserRestUsage userRestUsage = null;
    MyPushWorksAdapter adapter;
    List<String> pathList = new ArrayList<>();
    private static final int REQUEST_CODE_CHOOSE = 1;
    private String id;
    boolean buttonFlag;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_modify_video;
    }

    @Override
    public void initUI() {
        super.initUI();
        tvTitle.setText("展示设置");
        ibtnDelete.setVisibility(View.VISIBLE);
        //布局管理器所需参数，上下文
        for (int i = 0; i < 5; i++) {
            WorkTag tag = new WorkTag();
            tag.setName(500 + i + "");
            charmPosition.add(tag);
        }
        Intent intent = getIntent();
        isVedio = intent.getBooleanExtra("isVideo", true);
        id = intent.getStringExtra("id");
        bean = (ListpBean) intent.getSerializableExtra("ListpBean");
        refreshList(bean);
        if (!isVedio) {
            tvPush.setVisibility(View.VISIBLE);
            mRecyclerview.setVisibility(View.VISIBLE);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
            mRecyclerview.setLayoutManager(gridLayoutManager);
            adapter = new MyPushWorksAdapter(this, pathList, isVedio);
            adapter.setWorkListener(this);
            mRecyclerview.setAdapter(adapter);
        }
    }

    private void refreshList(ListpBean bean) {
        if (bean != null && bean.getPath() != null && !"".equals(bean.getPath())) {
            String string = bean.getPath().substring(1, bean.getPath().length());
            if (string.contains(",")) {
                String[] arr = string.split(",");
                for (String str : arr) {
                    pathList.add(str);
                }
            } else pathList.add(string);
        }
    }


    @Override
    public void refreshUI(int taskId, MSG msg) {
        super.refreshUI(taskId, msg);
        if (taskId == pushPhotoId) {
            if (msg.getData()) {
                EventBus.getDefault().post(new PhotoListEvent());
                finish();
            }
        }
        if (taskId == pushVedioId) {
            if (msg.getData()) {
                EventBus.getDefault().post(new PhotoListEvent());
                finish();
            }
        }
        if (taskId == deletePicId) {
            if (msg.getData()) {
                ToastUtil.showShort(this, "删除成功");
                EventBus.getDefault().post(new PhotoListEvent());
                userRestUsage.myInfo(myInfoId, Util.UserId);
            }
        }
        if (taskId == myInfoId) {
            if (msg.getData()) {
                if (msg.getObj() == null)
                    return;
                EventBus.getDefault().post(new WorkTag());
                ArtistsDetailedBean artistsDetailedBean = (ArtistsDetailedBean) msg.getObj();
                for (ListpBean listpBean : artistsDetailedBean.getListp()) {
                    if (bean.getId().equals(listpBean.getId())) {
                        pathList.clear();
                        refreshList(listpBean);
                        adapter.notifyDataSetChanged();
                    }
                }
            }
        }
        if (taskId == addPicId) {
            if (msg.getData())
                EventBus.getDefault().post(new PhotoListEvent());
                userRestUsage.myInfo(myInfoId, Util.UserId);
        }
        if (taskId == deleteAllId) {
            if (msg.getData()) {
                EventBus.getDefault().post(new PhotoListEvent());
                finish();
            }
        }
    }


    @OnClick({R.id.tvCharmTag, R.id.btnSave, R.id.ibtnDelete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvCharmTag:
                Intent intent = new Intent(this, HotTagActivity.class);
                intent.putExtra("tagType", 3);//0风格标签 1外貌标签 2体型标签 3魅力部位
                intent.putExtra("Tag", (Serializable) charmPosition);
                startActivityForResult(intent, Util.HOT_TAG);
                break;
            case R.id.btnSave:
                if (buttonFlag)
                    return;
                if ("".equals(etTitle.getText().toString().trim())) {
                    ToastUtil.showShort(this, "标题不能为空");
                    return;
                }
                if ("".equals(etDescribe.getText().toString().trim())) {
                    ToastUtil.showShort(this, "作品描述不能为空");
                    return;
                }
                params.put("title", etTitle.getText().toString().trim());
                params.put("title1", etDescribe.getText().toString().trim());
                if (isVedio) {
                    params.put("id", id);
                    params.put("title2", charm);
                    artistRestUsage.updateVedioWorks(pushVedioId, params);
                } else {
                    params.put("id", bean.getId());
                    params.put("tag", charm);
                    artistRestUsage.updateVedioWorks(pushPhotoId, params);
                }
                buttonFlag = true;
                break;
            case R.id.ibtnDelete:
                if (isVedio)
                    artistRestUsage.deleteAll(deleteAllId, id);
                else artistRestUsage.deleteAll(deleteAllId, bean.getId());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Util.HOT_TAG:
                if (data == null)
                    return;
                Bundle bundle = data.getExtras();
                checkCharmPosition = (List<WorkTag>) bundle.getSerializable("checkTag");
                charm = getString(checkCharmPosition);
                updateUI(layoutCharmTag, checkCharmPosition);
                break;
            case REQUEST_CODE_CHOOSE:
                if (resultCode == RESULT_OK) {
                    if (data == null)
                        return;
                    final List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    final Map<String, String> map = new HashMap<>();
                    map.put("id", bean.getId());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < path.size(); i++) {
                                pathList.add(path.get(i));
                                Bitmap bitmap = ImageUtils.compressImage(ImageUtils.getImageBitmap(path.get(i)));
                                String base64 = ImageUtils.bitmapToBase64(bitmap);
                                map.put("photoImgFile" + i, base64);
                            }
                            artistRestUsage.addPic(addPicId, map);
                        }
                    }).start();
                }
                break;
        }
    }

    //拼接tag
    private String getString(List<WorkTag> list) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                sb.append(list.get(i).getName());
                break;
            }
            sb.append(list.get(i).getName());
            sb.append(",");
        }
        return sb.toString();
    }

    private void updateUI(LinearLayout layout, List<WorkTag> tags) {
        layout.removeAllViews();
        for (int i = 0; i < tags.size(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.item_work_tag, null);
            CheckBox boxWorkTag = view.findViewById(R.id.boxWorkTag);
            boxWorkTag.setChecked(true);
            boxWorkTag.setClickable(false);
            boxWorkTag.setText(tags.get(i).getName());
            view.setPadding(0, 0, 25, 0);
            layout.addView(view);
        }
    }

    @Override
    public void workClick(int position, boolean isVideo) {

        if (position == pathList.size()) {
//                Picker.from(this)
//                        .count(9)
//                        .enableCamera(true)
//                        .setEngine(new GlideEngine())
//                        .forResult(REQUEST_CODE_CHOOSE);
            MultiImageSelector.create()
                    .showCamera(true)
                    .count(9 - pathList.size())
                    .multi()
                    .start(this, REQUEST_CODE_CHOOSE);

        }
    }


    @Override
    public void deletePhone(int position, String url) {
        artistRestUsage.deletePic(deletePicId, bean.getId(), url);
    }
}
